//
//  ShoppingCartViewController.m
//  OrderMeal
//
//  Created by 周浩 on 14-3-9.
//  Copyright (c) 2014年 周浩. All rights reserved.
//

#import "ShoppingCartViewController.h"
#import "AFHTTPRequestOperationManager.h"
#import "shoppingCartCell.h"
#import "MemberOrderController.h"
#import "MBProgressHUD.h"
#import "UIView+Toast.h"
#import "NonMemberOrderController.h"
@interface ShoppingCartViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    NSString *_memberID;
    NSMutableArray *_tableDataArray;//表格初始数据
    NSMutableArray *_selectedCell;//需要被删除的数据    MBProgressHUD *hud;
    BOOL _bottomViewisShow;
    MBProgressHUD *hud;//加载数据
    MBProgressHUD *hudModify;//修改数量
    int allFinished;
    int allModified;
    float totalPrice;
}
@property (strong, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet UILabel *totalPriceLabel;
@property (weak, nonatomic) IBOutlet UIButton *mergeShoppingBtn;

@end

@implementation ShoppingCartViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.deleteBtn.layer setCornerRadius:8.0];
    [self.payBtn.layer setCornerRadius:8.0];
    [self.mergeShoppingBtn.layer setCornerRadius:8.0];
    NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];
    _memberID=[userDefaults objectForKey:@"memberID"];//初始化
    _selectedCell = [[NSMutableArray alloc]init];
    _bottomViewisShow = 0;//默认底部view显示
    //接收通知
    self.tableView.delegate = self;
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reCalculate) name:@"cellTotalPrice Changed" object:nil];
    //删除合并购物车
}

-(void)reCalculate{
    float refreshTotalPrice = 0;
    for (int i = 0; i<[_tableDataArray count]; i++) {
        shoppingCartCell *cell = (shoppingCartCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
        refreshTotalPrice += [cell.cellTotalPrice floatValue]*(cell.checkbox.selected);
    }
    [self.totalPriceLabel setText:[NSString stringWithFormat:@"￥%.2f",refreshTotalPrice]];
}

- (void)refresh:(UITableView *)tableView
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self requestWithMemberID:_memberID];
    });
}
//刷新tableView
-(void)refreshTableView{
    self.refreshControl.attributedTitle = [[NSAttributedString alloc]initWithString:@"加载中"];
    [self requestWithMemberID:_memberID];
    [self performSelector:@selector(afterRefresh:) withObject:nil afterDelay:0.1];
    
}

-(void)afterRefresh:(id)obj{
    [self.refreshControl endRefreshing];
    for (int i = 0; i<_tableDataArray.count; i++) {
        shoppingCartCell *cell = (shoppingCartCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
        [cell setBackgroundColor:[UIColor colorWithRed:245.0f/255.0 green:245.0f/255.0 blue:245.0f/255.0 alpha:1.0]];
}

    self.refreshControl.attributedTitle = [[NSAttributedString alloc]initWithString:@"下拉刷新"];
}

-(void)selectedShoppingCart
{
    if (_memberID!=nil) {
        [self requestWithMemberID:_memberID];
    }
}


//获取购物车列表
-(void)requestWithMemberID:(NSString *)memberID
{
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    NSDictionary *parameters=@{
                               @"memberId" : memberID
                               };

    [manager GET:cartview_url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        [hud removeFromSuperview];

        NSString *responseStr = [operation.responseString stringByReplacingOccurrencesOfString:@"null" withString:@"\"\""];
        NSData *responseData = [responseStr dataUsingEncoding:NSUTF8StringEncoding];
        NSError *error;
        NSDictionary *responseObj = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
        if (![responseObj[@"retData"] isEqualToString:@""]) {
            _tableDataArray= responseObject[@"retData"][@"cartItems"];
            [self.tableView reloadData];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}

#pragma mark - request
//删除购物车
-(void)deleteWithMemberID:(NSString *)memberID
                   goodsid:(NSString *)goodsid
{
    
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    NSDictionary *parameters=@{
                               @"memberId" : memberID,
                               @"goodsid" :  goodsid
                               };
    
    [manager GET:cartGoodsDelete_url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
       
        NSNumber *status=responseObject[@"success"];
        
        if ([status isEqualToNumber:@1]) {
            shoppingCartCell *cell = (shoppingCartCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:allFinished-1 inSection:0]];
            [cell.checkbox setSelected:NO];
            allFinished--;
            if(allFinished == 0){
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"消息" message:@"删除成功" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
                [alert show];
                [_selectedCell removeAllObjects];
                [self performSelectorOnMainThread:@selector(refresh:) withObject:self.tableView waitUntilDone:NO];
                [self.bottomView removeFromSuperview];
            }
        }else{
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"消息" message:@"删除失败" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
            alert.delegate = self;
            alert.tag = 1;
            [alert show];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"消息" message:@"访问失败" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
        alert.delegate = self;
        alert.tag = 1;
        [alert show];
    }];
}

//修改商品份数
-(void)modifyWithMemberId:(NSString *)memberId
                  goodsid:(NSString *)goodsid
                 quantity:(NSString *)quantity
{
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    NSDictionary *parameters=@{
                                 @"memberId" : memberId,
                                 @"goodsid"  : goodsid,
                                 @"quantity" : quantity
                               };

    [manager GET:cartmerge_url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
       
        NSNumber *status=responseObject[@"success"];
        if ([status isEqualToNumber:@1]) {
           [self requestWithMemberID:_memberID];
            allModified --;
            if (allModified == 0) {
                [self performSegueWithIdentifier:@"提交订单" sender:nil];
                [hud removeFromSuperview];
            }
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"消息" message:@"修改发生错误" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }];
}

#pragma mark dataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _tableDataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    shoppingCartCell *cell=[tableView dequeueReusableCellWithIdentifier:@"CellShoppingCart"];
    [cell.numBtn.layer setBorderWidth:0.5];
    [cell.numBtn.layer setBorderColor:[[UIColor blackColor] CGColor]];
    NSDictionary *goodDetailInfo=_tableDataArray[indexPath.row];
    if (_memberID !=nil) {
        //原先数量
        cell.previousNum = [NSString stringWithFormat:@"%@",goodDetailInfo[@"quantity"] ];
        //当前数量
        [cell.numBtn setTitle:[NSString stringWithFormat:@"%@",goodDetailInfo[@"quantity"]] forState:UIControlStateNormal];
        cell.salesPrice.text=[NSString stringWithFormat:@"￥%@",goodDetailInfo[@"goods"][@"price"]];
        cell.name.text= goodDetailInfo[@"goods"][@"name"];
        int num = [[cell.numBtn currentTitle]intValue];
        float price = [goodDetailInfo[@"goods"][@"price"] floatValue];
        cell.cellTotalPrice = [NSString stringWithFormat:@"%.2f",num*price];
        
        cell.goodsid = [NSString stringWithFormat:@"%@",goodDetailInfo[@"goods"][@"id"]];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setBackgroundColor:[UIColor colorWithRed:245.0f/255.0 green:245.0f/255.0 blue:245.0f/255.0 alpha:1.0]];
        return cell;
    }else{
        //非会员购物车数据
        [cell.numBtn setTitle:goodDetailInfo[@"goodsQuantity"] forState:UIControlStateNormal];
        [cell.name setText:goodDetailInfo[@"goodsInfo"]];
        cell.goodsid = goodDetailInfo[@"goodsid"];
        [cell.salesPrice setText:[NSString stringWithFormat:@"￥%@",goodDetailInfo[@"goodsPrice"]]];
        [cell.remainingLabel setText:goodDetailInfo[@"goodsRemain"]];
        int num = [[cell.numBtn currentTitle]intValue];
        float price = [goodDetailInfo[@"goodsPrice"] floatValue];
        cell.cellTotalPrice = [NSString stringWithFormat:@"%.2f",num*price];
        [cell setBackgroundColor:[UIColor colorWithRed:245.0f/255.0 green:245.0f/255.0 blue:245.0f/255.0 alpha:1.0]];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.checkbox.selected = NO;
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    shoppingCartCell *cell = (shoppingCartCell *)[tableView cellForRowAtIndexPath:indexPath];
    cell.checkbox.selected = !cell.checkbox.selected;
    if (cell.checkbox.selected) {
        [cell setBackgroundColor:[UIColor colorWithRed:255.0f/255.0 green:251.0f/255.0 blue:244.0f/255.0 alpha:1.0]];
        //会员
        if (_memberID !=nil) {
            if (!_bottomViewisShow) {
                [self.view addSubview:self.bottomView];
                _bottomViewisShow = 0;
                [self.mergeShoppingBtn removeFromSuperview];
            }
        }else{
            if (!_bottomViewisShow) {
                [self.view addSubview:self.bottomView];
                [self.bottomView addSubview:self.mergeShoppingBtn];
                _bottomViewisShow = 0;
            }
            self.bottomView.frame = CGRectMake(self.bottomView.frame.origin.x, 422+self.tableView.contentOffset.y , 320,97);
        }
       
        [_selectedCell addObject:cell];
    }else{
        [self.allPickBtn setSelected:NO];
        [cell setBackgroundColor:[UIColor colorWithRed:245.0f/255.0 green:245.0f/255.0 blue:245.0f/255.0 alpha:1.0]];
        int isAllUnSelected = 0;
        for (int i = 0; i<_tableDataArray.count; i++) {
            shoppingCartCell *cell = (shoppingCartCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
            isAllUnSelected += cell.checkbox.selected;
        }
        if (!isAllUnSelected) {
            [self.bottomView removeFromSuperview];
        }
        
        [_selectedCell removeObject:cell];
    }
    
    totalPrice = 0.0f;
    for (int i = 0 ; i<[_selectedCell count]; i++) {
        shoppingCartCell *cellForPrice = _selectedCell[i];
        float price = [cellForPrice.cellTotalPrice floatValue];
        totalPrice += price;
    }
    [self.totalPriceLabel setText:[NSString stringWithFormat:@"￥%.2f",totalPrice]];

}


-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    self.bottomView.frame = CGRectMake(self.bottomView.frame.origin.x, 422+self.tableView.contentOffset.y , 320,97);
}


//删除按钮触发事件
- (IBAction)deleteGood:(UIButton *)sender {
    if (_memberID !=nil) {
        allFinished = [_selectedCell count];
        for (shoppingCartCell *cell in _selectedCell) {
            [self deleteWithMemberID:_memberID goodsid:cell.goodsid];
        }
    }else{
        NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"NonMemberShoppingCart-Info" ofType:@"plist"];
        NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
        for (shoppingCartCell *cell in _selectedCell) {
            NSDictionary *dict = @{@"goodsInfo": cell.name.text,
                                   @"goodsPrice":[cell.salesPrice.text substringFromIndex:1],
                                   @"goodsQuantity":[cell.numBtn currentTitle],
                                   @"goodsRemain":cell.remainingLabel.text,
                                   @"goodsid":cell.goodsid};
            [array removeObject:dict];
        }
        [array writeToFile:plistPath atomically:YES];
        [self.bottomView removeFromSuperview];
        dispatch_async(dispatch_get_main_queue(), ^{
            _tableDataArray = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
            [self.tableView reloadData];
            self.bottomView.frame = CGRectMake(self.bottomView.frame.origin.x, 422, 320,97);
            [_selectedCell removeAllObjects];
        });
    }
}

- (IBAction)submit:(UIButton *)sender {
    //会员
    if (_memberID != nil) {
        int allisNotModified = 1;
        for (shoppingCartCell *cell in _selectedCell) {
            if (![cell.previousNum isEqualToString:[cell.numBtn currentTitle]]) {
                allisNotModified = 0;
                break;
            }
        }
        //商品数量都没有被变价
        if (allisNotModified) {
            [self performSegueWithIdentifier:@"提交订单" sender:nil];
        }else{
            allModified = [_selectedCell count];
            hud.labelText = @"修改商品数量中";
            [self.view addSubview:hud];
            
            for (shoppingCartCell *cell in _selectedCell) {
                if (![cell.previousNum isEqualToString:[cell.numBtn currentTitle]]) {
                    [self modifyWithMemberId:_memberID goodsid:cell.goodsid quantity:[cell.numBtn currentTitle]];
                }
            }
        }
    }else{
        [self performSegueWithIdentifier:@"非会员购物车下单" sender:self];
    }
    //非会员购物车下单
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqual:@"提交订单"]) {
        MemberOrderController *memberOrderVC=segue.destinationViewController;
        memberOrderVC.goodsids = [[NSMutableArray alloc]init];
        memberOrderVC.selectedGoods = [[NSMutableArray alloc]init];
        memberOrderVC.totalPrice = self.totalPriceLabel.text;
        for (shoppingCartCell *cell in _selectedCell) {
            [memberOrderVC.goodsids addObject:cell.goodsid];
            [memberOrderVC.selectedGoods addObject:@{
                                                     @"goodsName":cell.name.text,
                                                     @"goodsPrice":cell.salesPrice.text,
                                                     @"goodsQuantity":[cell.numBtn currentTitle]
                                                     }];
        }
    }else if([segue.identifier isEqual:@"非会员购物车下单"]){
        NonMemberOrderController *nonmemberOrderVC =segue.destinationViewController;
        nonmemberOrderVC.goodsid = [[NSMutableArray alloc]init];
        nonmemberOrderVC.goodsNum = [[NSMutableArray alloc]init];
        [nonmemberOrderVC.goodsid addObject:@"1"];
        [nonmemberOrderVC.goodsNum addObject:@"2"];
    }
}


- (IBAction)selectAll:(UIButton *)sender {
    if (!sender.selected) {
        [sender setImage:[UIImage imageNamed:@"checkbox_selected.png"] forState:UIControlStateSelected];
        for (int i = 0; i<_tableDataArray.count; i++) {
            shoppingCartCell *cell = (shoppingCartCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
            [cell setBackgroundColor:[UIColor colorWithRed:255.0f/255.0 green:251.0f/255.0 blue:244.0f/255.0 alpha:1.0]];
            [cell.checkbox setSelected:YES];
        }
        [self.view addSubview:self.bottomView];
        [_selectedCell removeAllObjects];
        for (int i = 0; i<[_tableDataArray count]; i++) {
            [_selectedCell addObject:[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]]];
        }
        [self reCalculate];
    }else{
        [sender setImage:[UIImage imageNamed:@"checkbox_unselected.png"] forState:UIControlStateNormal];
        for (int i = 0; i<_tableDataArray.count; i++) {
            shoppingCartCell *cell = (shoppingCartCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
            [cell setBackgroundColor:[UIColor colorWithRed:245.0f/255.0 green:245.0f/255.0 blue:245.0f/255.0 alpha:1.0]];
            [cell.checkbox setSelected:NO];
        }
        [self.bottomView removeFromSuperview];
        [_selectedCell removeAllObjects];
        [self reCalculate];
    }
    sender.selected = !sender.selected;
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];
    _memberID=[userDefaults objectForKey:@"memberID"];//初始化
    if (_memberID!=nil) {
        hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeIndeterminate;
        hud.labelText = @"等待加载数据";
        [self requestWithMemberID:_memberID];
        
        UIView *view = [UIView new];
        [view setBackgroundColor:[UIColor clearColor]];
        [self.tableView setTableFooterView:view];
        //下拉刷新
        UIRefreshControl *refreshControl  = [[UIRefreshControl alloc]init];
        refreshControl.attributedTitle = [[NSAttributedString alloc]initWithString:@"下拉刷新"];
        [refreshControl addTarget:self action:@selector(refreshTableView) forControlEvents:UIControlEventValueChanged];
        self.refreshControl = refreshControl;
        
    }
    if (_memberID ==nil) {
        self.bottomView.frame = CGRectMake(0, 358, 320, 97);
        [self.bottomView removeFromSuperview];
        NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"NonMemberShoppingCart-Info" ofType:@"plist"];
        _tableDataArray = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
        [self.tableView reloadData];
    }
}



- (IBAction)mergeNonmemberShoppingCart:(id)sender {
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"请输入会员邮箱" message:@"" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:@"取消", nil];
    [alert setAlertViewStyle:UIAlertViewStylePlainTextInput];
    alert.delegate = self;
    alert.tag = 10;
    [alert show];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0 && alertView.tag == 10) {
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"NonMemberShoppingCart-Info" ofType:@"plist"];
        NSArray *nonMemberShoppingCartData = [[NSArray alloc]initWithContentsOfFile:plistPath];
        NSMutableArray *goodsidsArray = [[NSMutableArray alloc]init];
        NSMutableArray *goodsnumsArray = [[NSMutableArray alloc]init];
        for (NSDictionary *dic in nonMemberShoppingCartData) {
            [goodsidsArray addObject:dic[@"goodis"]];
            [goodsnumsArray addObject:dic[@"goodsQuantity"]];
        }
        NSDictionary *params = @{@"email":[alertView textFieldAtIndex:0].text,
                                 @"goodsids":[goodsidsArray componentsJoinedByString:@","],
                                 @"goodsnums":[goodsnumsArray componentsJoinedByString:@","]};
        [manager GET:cartListmerge_url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
            if ([responseObject[@"success"] isEqualToNumber:@1]) {
                [self.view makeToast:responseObject[@"msg"] duration:2.0 position:@"center"];
            }else{
                [self.view makeToast:responseObject[@"msg"] duration:2.0 position:@"center"];
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                [self.view makeToast:@"合并失败" duration:2.0 position:@"center"];
        }];
    }
}
@end

